#!/usr/bin/env bash

# 配置区 (用户可自行修改这些变量)
source $HOME/.config/hypr/configs/wallpaper.conf
# 生成格式匹配参数
find_args=()
for ext in "${EXTENSIONS[@]}"; do
    find_args+=(-iname "*.$ext" -o)
done
find_args=("${find_args[@]::${#find_args[@]}-1}")  # 移除最后一个 -o

if [ $1 ]; then
  if [ "$1" == "f" ]; then
    mode="fixed"
  elif [ "$1" == "r" ]; then
    mode="random"
  elif [ "$1" == "b" ]; then
    mode="bing"
  elif [ "$1" == "v" ]; then
    mode="video"
  elif [ "$1" == "k" ]; then
    # 杀死之前的随机进程
    pkill mpvpaper
    if [[ -f /tmp/swww_random.pid ]]; then
      kill -9 "$(cat /tmp/swww_random.pid)" 2>/dev/null
      rm /tmp/swww_random.pid
    fi
    echo "随机进程已kill"
    exit
  fi
else
  # 通过Wofi选择模式
  mode=$(printf "fixed\nrandom\nbing\nvideo" | wofi -d -p "选择壁纸模式:")
fi


case $mode in
    "fixed")
        # 杀死之前的随机进程
        $0 k

        swayimg -f -r $WALLPAPER_DIR -g --config=keys.gallery.Return="exec swww img % --transition-type any;exit"
        ;;

    "random")
        # 杀死之前的随机进程
        $0 k

        # 启动随机轮换进程
        (
            while true; do
                # 随机选择壁纸
                random_wallpaper=$(find "$WALLPAPER_DIR" -type f \( "${find_args[@]}" \) | shuf -n 1)
                
                if [[ -n $random_wallpaper ]]; then
                    swww img "$random_wallpaper" --transition-type any
                    sleep $INTERVAL
                else
                    notify-send "壁纸错误" "未找到可用壁纸！"
                    exit 1
                fi
            done
        ) &

        # 记录进程PID
        echo $! > /tmp/swww_random.pid
        notify-send "随机壁纸已启用" "轮换间隔: $INTERVAL 秒"
        ;;

    "bing")
        # 杀死之前的随机进程
        $0 k

        source $HOME/.config/hypr/scripts/bing_wallpaper.sh
        files=( $HOME/Pictures/bing_images/* )
        swww img ${files[-1]}  --transition-type any
        ;;
    "video")
        $0 k 
        mpvpaper -vs -o '--loop --no-audio video-sync=display-vdrop hwdec=auto panscan=1.0' '*' '/home/xy/Pictures/wpp/3533272074/芙宁娜furina.mp4' -f

esac
